#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<cstring>
#include"InetAddr.hpp"
using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "usage:" << argv[0] << "error" << endl;
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = htons(stoi(argv[2]));
    //创建
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd<0)
    {
        cout<<"create socket error"<<endl;
        exit(1);
    }
    //不需要显示绑定，会自己随机生产端口
    //建立连接
    struct sockaddr_in server;
    server.sin_port = serverport;
    server.sin_family = AF_INET;
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    int n = ::connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if(n<0)
    {
        cerr << "connect error" << endl;
        exit(1);
    }
    while(1)
    {
        string message;
        cout << "Enter:";
        getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());
        char buf[512];
        int n=read(sockfd, buf, sizeof(buf) - 1);
        if(n>0)
        {
            buf[n] = 0;
            cout << "server:" << buf << endl;
        }
        else 
        {
            break;
        }
    }
    ::close(sockfd);
    return 0;
}